<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-if="BUTTONS.add" type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button v-if="BUTTONS.import" type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button>
        <el-button v-if="BUTTONS.export" type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button v-if="BUTTONS.edit" type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button v-if="BUTTONS.delete" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <DetailDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { ExportObj, Code } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import DetailDrawer from "./detailDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, View, Upload } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useDateFormat } from "@vueuse/core";
import { dateRender, enumRender } from "@/hooks/useColumnRender";
import { ExportColType } from "@/enums/sysEnum";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { useDataStore } from "@/stores/modules/data";
import { useAuthButtons } from "@/hooks/useAuthButtons";
const dataStore = useDataStore();

const initVar = reactive({
  tbName: "repository",
  tbCnName: "仓库"
});

// ProTable 实例
const proTable = ref<ProTableInstance>();
const { BUTTONS } = useAuthButtons();

const initParam = reactive({
  // user_id: userStore.userInfo._id
});

const orgList = computed(() => dataStore.getOrgListByType("DEV"));
const isOrNotList = computed(() => dataStore.getEnumByCsName("IS_NOT"));
onMounted(() => {
  dataStore.findOrgList();
  dataStore.findEnumByCsName("IS_NOT");
});

const getTableList = (params: any) => {
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

// 表格配置项
const columns = reactive<ColumnProps<Code.Repository>[]>([
  { type: "index", label: "序号", width: 60 },
  { prop: "repository_id", label: "编号", width: 80 },
  { prop: "name", label: "仓库名称", minWidth: 180, align: "left", search: { el: "input", like: true } },
  { prop: "title", label: "仓库说明", minWidth: 200, align: "left", search: { el: "input", like: true } },
  {
    prop: "type",
    label: "仓库类别",
    width: 100,
    // 字典请求携带环境
    enum: () => apiService.findClassify("REP_TYPE"),
    fieldNames: { label: "name", value: "_id" }
  },
  // {
  //   prop: "language",
  //   label: "仓库语言",
  //   width: 100,
  //   // 字典请求携带环境
  //   enum: () => apiService.findClassify("REP_LANGUAGE"),
  //   fieldNames: { label: "name", value: "_id" }
  // },
  {
    prop: "product_id",
    label: "产品",
    minWidth: 120,
    enum: () => apiService.find("product", {}),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "_id" }
  },
  {
    prop: "sonar",
    label: "Sonar检查",
    width: 100,
    // 字典请求携带环境
    // enum: () => apiService.findClassify("IS_NOT"),
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "unit_test",
    label: "单元测试",
    width: 100,
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "org_id",
    label: "项目组",
    minWidth: 140,
    enum: orgList,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "_id" }
  },
  // {
  //   prop: "charge_user",
  //   label: "负责人",
  //   width: 100,
  //   enum: () => apiService.find("users", {}),
  //   fieldNames: { label: "userName", value: "_id" }
  // },
  {
    prop: "service_type",
    label: "产品/项目",
    width: 100,
    // 字典请求携带环境
    enum: () => apiService.findClassify("service_type"),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "state",
    label: "状态",
    width: 100,
    tag: true,
    // 字典请求携带环境
    enum: () => apiService.findClassify("DATA_STATE"),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "create_at",
    label: "创建时间",
    width: 120,
    render: dateRender
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 220 }
]);

// 删除信息
const deleteAccount = async (params: Code.Repository) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除仓库【${params.name}】`);
  proTable.value?.getTableList();
};

const getExcelConfig = (): ExportObj => {
  return {
    params: proTable.value?.totalParam,
    tableName: initVar.tbName,
    keyPropName: "repository_id",
    enumTypes: ["DATA_STATE", "REP_TYPE", "REP_LANGUAGE", "IS_NOT"],
    tableConfigs: [
      { tableName: "users", fields: ["_id", "userName"] },
      { tableName: "orgs", fields: ["_id", "name"] },
      { tableName: "product", fields: ["_id", "name"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "仓库编号", width: 8, ext: { prop: "repository_id", type: ExportColType.DEFAULT } },
      { header: "仓库名称", width: 20, ext: { prop: "name", type: ExportColType.DEFAULT } },
      { header: "仓库说明", width: 20, ext: { prop: "title", type: ExportColType.DEFAULT } },
      { header: "仓库地址", width: 50, ext: { prop: "url", type: ExportColType.DEFAULT } },
      {
        header: "仓库类别",
        width: 10,
        ext: { prop: "type", type: ExportColType.ENUM, key: "REP_TYPE", label: "name", value: "_id" }
      },
      {
        header: "语言",
        width: 10,
        ext: { prop: "language", type: ExportColType.ENUM, key: "REP_LANGUAGE", label: "name", value: "_id" }
      },
      {
        header: "Sonar检查",
        width: 8,
        ext: { prop: "sonar", type: ExportColType.ENUM, key: "IS_NOT" }
      },
      {
        header: "单元测试",
        width: 8,
        ext: { prop: "unit_test", type: ExportColType.ENUM, key: "IS_NOT" }
      },
      { header: "项目组", width: 18, ext: { prop: "org_id", type: ExportColType.TABLE, key: "orgs" } },
      {
        header: "负责人",
        width: 10,
        ext: { prop: "charge_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 12, ext: { prop: "create_at", type: ExportColType.DATE } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `仓库清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

// 导入数据
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "仓库",
    defaultTip: "仓库编码已有则跳过",
    coverTip: "仓库编号相同则覆盖",
    tempUrl: "/template/repository",
    getTableList: proTable.value?.getTableList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  dialogRef.value?.acceptParams(params);
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof DetailDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Code.Repository> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
